
# from spit.models import Spit
# from tensquare.apps.spit.models import Spit
# from rest_framework import serializers
import random

from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from .models import Spit

# class SpitSerializer(serializers.DocumentSerializer):
class SpitSerializer(serializers.ModelSerializer):

    class Meta:
        model = Spit
        fields = "__all__"

    def create(self, validated_data):

        #     spit = super().create(validated_data)
        # except Exception as e:
        num = random.randint(100,900)
        count = Spit.objects.all().count()
        spit = Spit()
        spit.content = validated_data['content']
        spit.id = count +1
        spit.nickname = num
        spit.avatar = ''
        spit.save()


        try:
            user = self.context["request"].user
        except:
            user = None

        #    判断是否是评论别人
        if spit.parent:
            # 评论别人必须登陆
            if user and user.is_authenticated:
                spit.userid = str(user.id)
                spit.nickname = user.nickname if user.nickname else user.username
                spit.avatar = user.avatar
                spit.save()
                spit.parent.comment += 1
                spit.parent.save()
                return spit
            else:
                raise ValidationError('未登录')
        else:
            return spit

